package cn.fl.riskctrl.service.impl;

import cmm.comm.facade.framework.api.ISysCtrlCfgApiService;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.condition.PrjCstBscInfoQueryCondition;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjCstBscInfoService;
import cn.fl.project.vo.PrjBscInfoVO;
import cn.fl.project.vo.PrjCstBscInfoVO;
import cn.fl.riskctrl.service.IRskCtrlCpService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import fl.constant.facade.framework.constant.DictionaryConstant;
import fl.constant.facade.framework.constant.SysCtrlCfgConstant;
import fl.constant.facade.framework.constant.SystemConstant;
import fl.customer.facade.customer.api.ICustomerApiService;
import fl.customer.facade.customer.api.ICustomerQueryApiService;
import fl.customer.facade.customer.condition.CstBankQueryCondition;
import fl.customer.facade.customer.dto.CstBankDTO;
import fl.customer.facade.customer.dto.CstBscInfoDTO;
import fl.customer.facade.customer.dto.CstNpBscInfoDTO;
import fl.riskctrl.facade.riskctrl.api.IRiskCtrlCpApiService;
import fl.riskctrl.facade.riskctrl.condition.RskCtrlIsCorrectQC;
import fl.riskctrl.facade.riskctrl.dto.DataResultDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 风控服务接口实现
 * @author FUJINGRUN
 */
@Service
public class RskCtrlCpServiceImpl implements IRskCtrlCpService {

	private static final Logger logger = LoggerFactory.getLogger(RskCtrlCpServiceImpl.class);

	/**风控API服务*/
	@Autowired
	public IRiskCtrlCpApiService riskCtrlCpApiService;
	/**项目服务*/
	@Autowired
	public IPrjBscInfoService prjBscInfoService;
	/**客户服务*/
	@Autowired
	public ICustomerApiService customerApiService;
	/**项目客户服务*/
	@Autowired
	public IPrjCstBscInfoService prjCstBscInfoService;
	/**客户服务*/
	@Autowired
	public ICustomerQueryApiService customerQueryApiService;
	/**系统配置服务*/
	@Autowired
	public ISysCtrlCfgApiService sysCtrlCfgApiService;

	@Override
	public DataResultDTO getRiskCtrlIsCorrect(Long prjId, Long cstId) throws BaseException {
		RskCtrlIsCorrectQC qc = new RskCtrlIsCorrectQC();
		qc.setSysCd(CurrentThreadContext.getFlServiceSysCd());
		qc.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
		List<RskCtrlIsCorrectQC> rskCtrlList = new ArrayList<>();
		this.setRiskCtrl(prjId, cstId, qc, rskCtrlList);
		this.setBankInfo(prjId, cstId, qc, rskCtrlList);
		String loadAllCd = PropertiesCacheUtils.getProperty(SysCtrlCfgConstant.RISK_CTRL_LOAD_ALL_SWITCH_CD);
		Map<String, String> map = this.getSwitch(loadAllCd);
		return this.riskCtrlCpApiService.getRiskCtrlIsCorrect(qc, Boolean.valueOf(map.get(loadAllCd)));
	}

	@Override
	public DataResultDTO checkZZCIsCorrect(Long prjId, Long cstId) throws BaseException {
		RskCtrlIsCorrectQC qc = new RskCtrlIsCorrectQC();
		qc.setSysCd(CurrentThreadContext.getFlServiceSysCd());
		qc.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
		this.setNpInfo(prjId, cstId, qc);
		return this.riskCtrlCpApiService.checkZZCIsCorrect(qc);
	}

	@Override
	public DataResultDTO checkXjIsCorrect(Long prjId, Long cstId) throws BaseException {
		RskCtrlIsCorrectQC qc = new RskCtrlIsCorrectQC();
		qc.setSysCd(CurrentThreadContext.getFlServiceSysCd());
		qc.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
		this.setNpInfo(prjId, cstId, qc);
		return this.riskCtrlCpApiService.checkXjIsCorrect(qc);
	}

	@Override
	public DataResultDTO checkSynthMobileIsCorrect(Long prjId, Long cstId) throws BaseException {
		RskCtrlIsCorrectQC qc = new RskCtrlIsCorrectQC();
		qc.setSysCd(CurrentThreadContext.getFlServiceSysCd());
		qc.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
		this.setNpInfo(prjId, cstId, qc);
		return this.riskCtrlCpApiService.checkSynthMobileIsCorrect(qc);
	}

	@Override
	public DataResultDTO checkSynthScoreIsCorrect(Long prjId, Long cstId) throws BaseException {
		RskCtrlIsCorrectQC qc = new RskCtrlIsCorrectQC();
		qc.setSysCd(CurrentThreadContext.getFlServiceSysCd());
		qc.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
		this.setNpInfo(prjId, cstId, qc);
		return this.riskCtrlCpApiService.checkSynthScoreIsCorrect(qc);
	}

	//*********************************************设置担保人数据*****************************************//
	/**
	 * 设置承租人和担保人数据
	 * @param id 项目ID
	 * @param qc 查询条件
	 * @param rskCtrlList 担保人集合
	 * @param rskCtrlList
	 */
	private void setRiskCtrl(Long prjId, Long cstId, RskCtrlIsCorrectQC qc, List<RskCtrlIsCorrectQC> rskCtrlList){
		//查询项目信息中的客户
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		Long userId = CurrentThreadContext.getCurrentUserId();
		List<Long> cstIds = new ArrayList<>();//客户查询集合
		cstIds.add(cstId);
		//检查下有没有担保人
		String dbrDic = PropertiesCacheUtils.getProperty(DictionaryConstant.CODE_GRP_CST_RL_TYP_CD_DBR);
		String zrrDic = PropertiesCacheUtils.getProperty(DictionaryConstant.CODE_GRP_CST_TYP_CD_NP);
		PrjCstBscInfoQueryCondition PrjCstBscInfoQueryCondition  = new PrjCstBscInfoQueryCondition();
		PrjCstBscInfoQueryCondition.setPrjId(prjId);
		PrjCstBscInfoQueryCondition.setCstTypCd(zrrDic);
		PrjCstBscInfoQueryCondition.setCstRlTyp(dbrDic);
		List<PrjCstBscInfoVO> prjCstBscInfoVOList = this.prjCstBscInfoService.searchList(PrjCstBscInfoQueryCondition);
		if(CollectionUtils.isNotEmpty(prjCstBscInfoVOList)){
			for (PrjCstBscInfoVO prjCstBscInfoVO : prjCstBscInfoVOList) {
				Long cstIdT1 = prjCstBscInfoVO.getCstId();
				if(cn.cmm.base.framework.utils.StringUtils.isEmpty(cstIdT1))continue;
				if (!cstIds.contains(cstIdT1)) {
					cstIds.add(cstIdT1);
				}
			}
		}
		//查询担保人信息
		qc.setCrtUsrId(userId);
		qc.setCstId(cstId);
		qc.setDataId(prjId);
		this.setRskCtrlIsCorrectQCInfo(qc, prjId);

		List<CstBscInfoDTO> cstList = this.customerQueryApiService.selectCstBscInfoByIds(cstIds, orgCd);
		CstNpBscInfoDTO cstNpBscInfoDTO = null;
		RskCtrlIsCorrectQC qcSub = null;
		for (CstBscInfoDTO cstBscInfoDTO : cstList) {
			Long cId = cstBscInfoDTO.getId();
			cstNpBscInfoDTO = cstBscInfoDTO.getCstNpBscInfoDTO();
			if(cstId.equals(cId)){//说明是承租人,其它为担保人
				qc.setCertNo(cstBscInfoDTO.getCertNo());
				qc.setName(cstBscInfoDTO.getCstNm());
				qc.setPhone(cstNpBscInfoDTO.getMp1());
			}else{
				qcSub = new RskCtrlIsCorrectQC();
				qcSub.setCertNo(cstBscInfoDTO.getCertNo());
				qcSub.setName(cstBscInfoDTO.getCstNm());
				qcSub.setPhone(cstNpBscInfoDTO.getMp1());
				qcSub.setCrtUsrId(userId);
				qcSub.setCstId(cId);
				qcSub.setDataId(prjId);
				rskCtrlList.add(qcSub);
			}
		}
	}

	/**
	 * 设置承租人和担保人银行卡号
	 * @param id 项目ID
	 * @param qc 查询条件
	 * @param rskCtrlList 担保人集合
	 * @param rskCtrlList
	 */
	private void setBankInfo(Long prjId, Long cstId, RskCtrlIsCorrectQC qc, List<RskCtrlIsCorrectQC> rskCtrlList){
		//查询项目信息中的客户
		List<Long> cstIdList = new ArrayList<>();
		cstIdList.add(cstId);

		List<String> certNoList = new ArrayList<>();
		certNoList.add(qc.getCertNo());

		List<String> accNameList = new ArrayList<>();
		accNameList.add(qc.getName());
		//检查担保人是否有
		if(CollectionUtils.isNotEmpty(rskCtrlList)){
			for (RskCtrlIsCorrectQC rskCtrlIsCorrectQC : rskCtrlList) {
				cstIdList.add(rskCtrlIsCorrectQC.getCstId());
				certNoList.add(rskCtrlIsCorrectQC.getCertNo());
				accNameList.add(rskCtrlIsCorrectQC.getName());
			}
		}

		CstBankQueryCondition cstBankQueryCondition = new CstBankQueryCondition();
		cstBankQueryCondition.setCstIdList(cstIdList);
		cstBankQueryCondition.setCertNoList(certNoList);
		cstBankQueryCondition.setAccNmList(accNameList);

		List<CstBankDTO> bankList = this.customerQueryApiService.searchCstBankList(cstBankQueryCondition);
		Map<Long, List<String>> bankMap = new HashMap<>();
		if(CollectionUtils.isNotEmpty(bankList)){
			for (CstBankDTO cstBankDTO : bankList) {
				Long cId = cstBankDTO.getCstId();
				String accNo = cstBankDTO.getAccNo();
				if(bankMap.containsKey(cId)){
					bankMap.get(cId).add(accNo);
				}else{
					List<String> newTemList = new ArrayList<>();
					newTemList.add(accNo);
					bankMap.put(cId, newTemList);
				}
			}
		}

		if(CollectionUtils.isMapNotEmpty(bankMap)){
			List<String> bkList = bankMap.get(cstId);
			if(CollectionUtils.isNotEmpty(bkList)){
				qc.setCardNos(bkList);
			}

			if(CollectionUtils.isNotEmpty(rskCtrlList)){
				for (RskCtrlIsCorrectQC rskCtrlIsCorrectQC : rskCtrlList) {
					Long cId = rskCtrlIsCorrectQC.getCstId();
					List<String> bkTemList = bankMap.get(cId);
					if(CollectionUtils.isNotEmpty(bkTemList)){
						rskCtrlIsCorrectQC.setCardNos(bkTemList);
					}
				}
			}
		}
	}



	/**
	 * 设置承租人数据
	 * @param id 项目ID
	 * @param qc 查询条件
	 * @param rskCtrlList
	 */
	public void setNpInfo(Long prjId, Long cstId, RskCtrlIsCorrectQC qc){
		//查询项目信息中的客户
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		Long userId = CurrentThreadContext.getCurrentUserId();
		List<Long> cstIds = new ArrayList<>();//客户查询集合
		cstIds.add(cstId);
		//查询担保人信息
		qc.setCrtUsrId(userId);
		qc.setCstId(cstId);
		qc.setDataId(prjId);
		this.setRskCtrlIsCorrectQCInfo(qc, prjId);

		List<CstBscInfoDTO> cstList = this.customerQueryApiService.selectCstBscInfoByIds(cstIds, orgCd);
		CstNpBscInfoDTO cstNpBscInfoDTO = null;
		for (CstBscInfoDTO cstBscInfoDTO : cstList) {
			cstNpBscInfoDTO = cstBscInfoDTO.getCstNpBscInfoDTO();
			qc.setCertNo(cstBscInfoDTO.getCertNo());
			qc.setName(cstBscInfoDTO.getCstNm());
			qc.setPhone(cstNpBscInfoDTO.getMp1());
		}
	}

	/**
	 * 设置担保人数据
	 * @param id 项目ID
	 * @param qc 查询条件
	 * @param rskCtrlList
	 */
	private void setDbrInfo(Long prjId, Long cstId, List<RskCtrlIsCorrectQC> rskCtrlList){
		//查询项目信息中的客户
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		Long userId = CurrentThreadContext.getCurrentUserId();
		List<Long> cstIds = new ArrayList<>();//客户查询集合
		//检查下有没有担保人
		String dbrDic = PropertiesCacheUtils.getProperty(DictionaryConstant.CODE_GRP_CST_RL_TYP_CD_DBR);
		String zrrDic = PropertiesCacheUtils.getProperty(DictionaryConstant.CODE_GRP_CST_TYP_CD_NP);
		PrjCstBscInfoQueryCondition PrjCstBscInfoQueryCondition  = new PrjCstBscInfoQueryCondition();
		PrjCstBscInfoQueryCondition.setPrjId(prjId);
		PrjCstBscInfoQueryCondition.setCstTypCd(zrrDic);
		PrjCstBscInfoQueryCondition.setCstRlTyp(dbrDic);
		List<PrjCstBscInfoVO> prjCstBscInfoVOList = this.prjCstBscInfoService.searchList(PrjCstBscInfoQueryCondition);
		if(CollectionUtils.isNotEmpty(prjCstBscInfoVOList)){
			for (PrjCstBscInfoVO prjCstBscInfoVO : prjCstBscInfoVOList) {
				Long cstIdT1 = prjCstBscInfoVO.getCstId();
				if(cn.cmm.base.framework.utils.StringUtils.isEmpty(cstIdT1))continue;
				if (!cstIds.contains(cstIdT1)) {
					cstIds.add(cstIdT1);
				}

			}
		}
		if(CollectionUtils.isEmpty(cstIds)){
			return;
		}
		//查询担保人信息
		List<CstBscInfoDTO> cstList = this.customerQueryApiService.selectCstBscInfoByIds(cstIds, orgCd);
		CstNpBscInfoDTO cstNpBscInfoDTO = null;
		RskCtrlIsCorrectQC qcSub = null;
		for (CstBscInfoDTO cstBscInfoDTO : cstList) {
			Long cId = cstBscInfoDTO.getId();
			cstNpBscInfoDTO = cstBscInfoDTO.getCstNpBscInfoDTO();
			qcSub = new RskCtrlIsCorrectQC();
			qcSub.setCertNo(cstBscInfoDTO.getCertNo());
			qcSub.setName(cstBscInfoDTO.getCstNm());
			qcSub.setPhone(cstNpBscInfoDTO.getMp1());
			qcSub.setCrtUsrId(userId);
			qcSub.setCstId(cId);
			qcSub.setDataId(prjId);
			rskCtrlList.add(qcSub);
		}
	}
	
	/**获取开关*/
	private Map<String, String> getSwitch(String loadAllCd){
		String defOrgCd = PropertiesCacheUtils.getProperty(SystemConstant.FL_ORG_CD);
		//获取总开关, 如果关闭则按照正常情况返回
		List<String> ctrlCfgCodes = new ArrayList<>();
		ctrlCfgCodes.add(loadAllCd);
		Map<String, String> map = this.sysCtrlCfgApiService.searchSysCtrlCfgByCtrlCodes(ctrlCfgCodes, CurrentThreadContext.getFlServiceSysCd(), defOrgCd);
		//获取是否全部加载数据开关
		if(CollectionUtils.isMapEmpty(map)){
			map = new HashMap<>();
		}
		return map;
	}

	@Override
	public void setCstIdForView(Long prjId, ModelAndView view) throws BaseException {
		// 查询项目信息中的客户
		PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(prjId);
		if (null == prjBscInfoVO) {
			BaseLogUtils.info(logger, "setCstIdForView", "根据ID未获取到项目信息数据." + prjId);
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "根据ID未获取到项目信息数据.");
		}
		Long cstId = prjBscInfoVO.getCstId();
		Map<Long, String> dbrMap = new HashMap<>();
		// 检查下有没有担保人
		String dbrDic = PropertiesCacheUtils.getProperty(DictionaryConstant.CODE_GRP_CST_RL_TYP_CD_DBR);
		String zrrDic = PropertiesCacheUtils.getProperty(DictionaryConstant.CODE_GRP_CST_TYP_CD_NP);
		PrjCstBscInfoQueryCondition PrjCstBscInfoQueryCondition = new PrjCstBscInfoQueryCondition();
		PrjCstBscInfoQueryCondition.setPrjId(prjId);
		PrjCstBscInfoQueryCondition.setCstTypCd(zrrDic);
		PrjCstBscInfoQueryCondition.setCstRlTyp(dbrDic);
		List<PrjCstBscInfoVO> prjCstBscInfoVOList = this.prjCstBscInfoService.searchList(PrjCstBscInfoQueryCondition);
		if (CollectionUtils.isNotEmpty(prjCstBscInfoVOList)) {
			for (PrjCstBscInfoVO prjCstBscInfoVO : prjCstBscInfoVOList) {
				Long cstIdT1 = prjCstBscInfoVO.getCstId();
				String cstNm = prjCstBscInfoVO.getCstNm();
				if(cn.cmm.base.framework.utils.StringUtils.isEmpty(cstIdT1))continue;
				if (!dbrMap.containsKey(cstIdT1)) {
					dbrMap.put(cstIdT1, cstNm);
				}
			}
		}
		view.addObject("zx_cstid", cstId);
		JSONArray zxDbrId = new JSONArray();
		JSONObject obj = null;
		for (Map.Entry<Long, String> m : dbrMap.entrySet()) {
			obj = new JSONObject();
			obj.put("id", m.getKey());
			obj.put("name", m.getValue());
			zxDbrId.add(obj);
		}
		view.addObject("zx_dbrid", zxDbrId.toJSONString());
	}

	/**
	 * 设置风控查询条件中指定要的参数,主要是区分数据使用,不同事业部的征信规则不同,用以区分规则算出来的结果
	 * @param qc 征信查询条件
	 * @param prjId 项目ID
	 */
	public void setRskCtrlIsCorrectQCInfo(RskCtrlIsCorrectQC qc, Long prjId){
		try {
			PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(prjId);
			if(null != prjBscInfoVO){
				qc.setBuOrgCd(prjBscInfoVO.getBuOrgCd());
				qc.setOrgCd(prjBscInfoVO.getCstMgrOrgCd());
				List<String> busTypCdList = new ArrayList<>();
				busTypCdList.add(prjBscInfoVO.getPrjTypCd());
				qc.setBusTypCdList(busTypCdList);
			}
		} catch (Exception e) {
			BaseLogUtils.info(logger, "setRskCtrlIsCorrectQCInfo", "设置征信查询对象组织架构参数失败!", CurrentThreadContext.getCurrentUserName(), e);
		}
	}
}
